// 开始查看考试习题
//  HBProductCommitmentController.m
//  HarBowTwo
//
//  Created by hbzzc on 16/9/1.
//  Copyright © 2016年 zzc. QQ：1457288727，All rights reserved.
//

#import "HBProductCommitmentController.h"
#import <WebKit/WebKit.h>
#import "QuickLookViewController.h"
#import "DocumentInteractionViewController.h"

@interface HBProductCommitmentController ()<WKNavigationDelegate,UIScrollViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate>
@property (nonatomic,strong)NSURL *fileURL;
@property (nonatomic, strong) WKWebView * webView;

@property (nonatomic, strong) NSString *minDurationString; //看这个模块需要的时间
@property (nonatomic, strong) NSString *startTimeString; //开始时间
@property (nonatomic, strong) NSString *endTitmeString; //开始时间
@end

@implementation HBProductCommitmentController
- (void)dealloc
{
    self.webView.navigationDelegate = nil;
    [self.webView removeFromSuperview];
    self.webView = nil;
    self.webView.scrollView.delegate = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    self.navigationController.navigationBar.hidden = NO;
}

// 释放scrollView 强引用！！

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.webView.scrollView.delegate = nil;
    NSString *studyStr;
    self.endTitmeString = [WKFTime getNowTimeTimestamp];
    NSInteger statrInt = [self.startTimeString integerValue];
    NSInteger endrInt = [self.endTitmeString integerValue];
    NSInteger numberInt = endrInt - statrInt;
    NSInteger minString = [self.minString integerValue]*60; //服务器跟的时间
//    if (KIsBlankString(self.minString)) {
//        studyStr = @"100";
//    }
//    if (numberInt >= minString) {
//        studyStr = @"100";
//    } else {
//        studyStr = @"0";
//    }
    
    [self studyTimeAction:studyStr];
}

#pragma mark - 提交学习进度信息
- (void)studyTimeAction:(NSString *)timeString {
    
    if (_courseId.length == 0) {
        return;
    } else if (_minString.length == 0){
        return;
    }
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kUser_key];
    
    NSDictionary *dict = @{
                           @"coursewareId" : _courseId, //课件id
                           @"studyState" : timeString, //
                           @"playTime" : @"-1",
                           @"memberId": token
                           }; //页数
    NSString *urlString = [NSString stringWithFormat:@"%@%@",uHostURL,@"learn/setStudyState"];
    [EPProgressHUD show];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:urlString parameters:dict success:^(id obj) {
        [EPProgressHUD dismiss];
       NSDictionary *dic = (NSDictionary *)obj;
        NSString *errorcodeString = dic[@"errorcode"];
        if ([dic[@"data"] isEqual:[NSNull null]]) {
            return;
        }
        DLog(@"%@",obj);
        if (![errorcodeString isEqualToString:@"9999"]) {
            return;
        }
    } fail:^(NSError *error) {
        [EPProgressHUD dismiss];
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.title;
    WKWebView * webview = [[WKWebView alloc] initWithFrame:self.view.bounds];
    webview.navigationDelegate = self;
    webview.scrollView.delegate = self;
    [self.view addSubview:webview];
//    [EPProgressHUD show];
    [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.fileURLString]]];
    self.webView = webview;
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
//    [EPProgressHUD dismiss];
//    document.documentElement.scrollHeight    获取高度
//    document.documentElement.innerHTML       获取当前网页的html
//    document.location.href                   当前URL
//    document.documentElement.innerText       获取内容

    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
//    NSURL *targetURL = [NSURL URLWithString:self.fileURLString];
//    
//    NSString *docPath = [self documentsDirectoryPath];
//    NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, [targetURL lastPathComponent]];
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    BOOL hasDownLoad= [fileManager fileExistsAtPath:pathToDownloadTo];
//    if (hasDownLoad) {
//        self.fileURL = [NSURL fileURLWithPath:pathToDownloadTo];
//        QLPreviewController *qlVC = [[QLPreviewController alloc]init];
//        qlVC.delegate = self;
//        qlVC.dataSource = self;
//        [self.navigationController pushViewController:qlVC animated:YES];
//        //
//    }
//    else {
//        NSURL *targetURL = [NSURL URLWithString:self.fileURLString];
//        
//        NSData *fileData = [[NSData alloc] initWithContentsOfURL:targetURL];
//        // Get the path to the App's Documents directory
//        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
//        [fileData writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, [targetURL lastPathComponent]] atomically:YES];
//        NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
//        [webView loadRequest:request];
//    }
    
    NSLog(@"webViewDidFinishLoad");
    
}

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}

- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    return self.fileURL;
}

- (void)previewControllerWillDismiss:(QLPreviewController *)controller {
    NSLog(@"previewControllerWillDismiss");
}

- (void)previewControllerDidDismiss:(QLPreviewController *)controller {
    NSLog(@"previewControllerDidDismiss");
}

- (BOOL)previewController:(QLPreviewController *)controller shouldOpenURL:(NSURL *)url forPreviewItem:(id <QLPreviewItem>)item{
    return YES;
}

- (CGRect)previewController:(QLPreviewController *)controller frameForPreviewItem:(id <QLPreviewItem>)item inSourceView:(UIView * __nullable * __nonnull)view{
    return CGRectZero;
}

- (NSString *)documentsDirectoryPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];
    return documentsDirectoryPath;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y > 100) {
        self.navigationItem.title = self.webView.title;
    }else{
        self.navigationItem.title = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
